package cm.tl.pms.util.fileParser.pdf;

import org.apache.commons.lang.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cm.tl.pms.util.fileParser.pdf.ValidationUtil.isValidNumber;

public class PDFTableParser {


    public static void main(String[] args) {
//        File pdfFile = new File("C:\\Users\\Lenovo\\Desktop\\0904中化信息技术有限公司.pdf");
//        File pdfFile = new File("C:\\Users\\Lenovo\\Documents\\WeChat Files\\wxid_2tswj262d0ye22\\FileStorage\\File\\2024-11\\测试用财务报表\\0912中化现代农业有限公司.pdf");
//        File pdfFile = new File("C:\\Users\\Lenovo\\Documents\\WeChat Files\\wxid_2tswj262d0ye22\\FileStorage\\File\\2024-12\\人行征信报告\\tes\\北京展拓置业有限公司企业信用报告（授信机构版）.pdf");
        File pdfFile = new File("C:\\Users\\Lenovo\\Documents\\WeChat Files\\wxid_2tswj262d0ye22\\FileStorage\\File\\2024-12\\桂林橡胶机械有限公司\\桂林橡胶机械有限公司信用报告（授信机构版）.pdf");
        try {
            Map<String, Object> result = PDFTableParser.parseCreditReport(pdfFile);
            // 输出解析结果
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    // 解析企业信用报告表格
    public static Map<String, Object> parseCreditReport(File pdfFile) throws IOException {
        PDDocument document = PDDocument.load(pdfFile);
        PDFTextStripper stripper = new PDFTextStripper() {
            @Override
            protected void writeString(String text, List<TextPosition> textPositions) throws IOException {
                // 在这里可以对提取的文本进行进一步处理，如果需要的话
                super.writeString(text, textPositions);
            }
        };
        String text = stripper.getText(document);

        System.out.println(text);
        document.close();
        // 将文本按行分割
        String[] lines = text.split("\\r?\\n");

//        System.out.println("按行分割后的文本:");
//        for (String line : lines) {
//            // 过滤掉空行和空白字符
//            if (!line.trim().isEmpty()) {
//                System.out.println(line);
//            }
//        }

        Map<String, Object> result = new HashMap<>();

        try {
            // 解析 报告基本信息
            parseFileBasicInfo(lines, result);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("解析报告基本信息时发生错误: " + e);
        }

        try {
            // 解析 身份标识
            parseIdentityInfo(lines, result);
        } catch (Exception e) {
            System.err.println("解析身份标识时发生错误: " + e.getMessage());
        }

        try {
            // 解析 基本信息
            parseBasicInfo(lines, result);
        } catch (Exception e) {
            System.err.println("解析基本信息时发生错误: " + e.getMessage());
        }

        try {
            // 解析 信息概要
            parseInfoSummary(lines, result);
        } catch (Exception e) {
            System.err.println("解析信息概要时发生错误: " + e.getMessage());
        }

        try {
            // 解析 相关还款责任信息概要
            parseRefundDetails(lines, result);
        } catch (Exception e) {
            System.err.println("解析相关还款责任信息概要时发生错误: " + e.getMessage());
        }

        try {
            // 解析 借贷交易和担保交易
            parseCreditAndGuaranteeTransactions(lines, result);
        } catch (Exception e) {
            System.err.println("解析借贷交易和担保交易时发生错误: " + e.getMessage());
        }

        try {
            // 解析 记录统计
            parseOtherDetails(lines, result);
        } catch (Exception e) {
            System.err.println("解析记录统计时发生错误: " + e.getMessage());
        }

        try {
            // 解析 负债历史
            parseLiabilitiesHistory(lines, result);
        } catch (Exception e) {
            System.err.println("解析负债历史时发生错误: " + e.getMessage());
        }

        try {
            // 解析 未结清信贷及授信信息概要
            parseCredit(lines, result);
        } catch (Exception e) {
            System.err.println("解析未结清信贷及授信信息概要时发生错误: " + e);
        }
        return result;
    }

    private static void parseRefundDetails(String[] lines, Map<String, Object> result) {
        String loanDeal1 = "0.0";
        String loanDeal2 = "0.0";
        boolean foundFirstSummary = false;

        for (int i = 0; i < lines.length; i++) {
            if (lines[i].contains("相关还款责任信息概要")) {
                while (i < lines.length && !lines[i].contains("合计")) {
                    i++;
                }
                if (i < lines.length && lines[i].startsWith("合计")) {
                    loanDeal1 = lines[i].split(" ")[6];
                    foundFirstSummary = true;
                }
            } else if (foundFirstSummary && lines[i].contains("还款责任金额 账户数 余额 关注类余额 不良类余额")) {
                while (i < lines.length && !lines[i].contains("合计")) {
                    i++;
                }
                if (i < lines.length && lines[i].startsWith("合计")) {
                    loanDeal2 = lines[i].split(" ")[3];
                }
                break;
            }
        }

        double doubleLoanDeal1 = Double.parseDouble(loanDeal1);
        double doubleLoanDeal2 = Double.parseDouble(loanDeal2);
        // 使用 DecimalFormat 格式化结果
        DecimalFormat df = new DecimalFormat("0.00");
        String formattedSum = df.format(doubleLoanDeal1 + doubleLoanDeal2);
        result.put("担保交易-总余额", formattedSum);
    }

    private static void parseCredit(String[] lines, Map<String, Object> result) {
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].contains("正常类 关注类 不良类 合计")) {
                System.out.println("*******  当前的索引值  " + i);
                i++;
                if (lines[i].contains("账户数 余额 账户数 余额 账户数 余额 账户数 余额")) {
                    int startIndex = i;
                    boolean sign = true;
                    while (sign) {
                        i++;
                        if (lines[i].startsWith("合计")) {
                            String oldValue = result.getOrDefault("不良类金额-合计", "0.000").toString();
                            String newValue = lines[i].split(" ")[6];
                            System.out.println("=============newValue: " + newValue + " oldValue: " + oldValue);
                            if (StringUtils.isNotBlank(newValue) && isValidNumber(newValue) && !"0.000".equals(oldValue)) {
                                newValue = new BigDecimal(oldValue).add(new BigDecimal(newValue)).toString();
                            }
                            result.put("不良类金额-合计", newValue);
                            getTrueOrFalse(result, newValue, "不良类金额-合计-有", "不良类金额-合计-无");

                            //result.put("关注类金额-合计", lines[i].split(" ")[4]);
                            String oldValue1 = result.getOrDefault("关注类金额-合计", "0.000").toString();
                            String newValue1 = lines[i].split(" ")[4];
                            if (StringUtils.isNotBlank(newValue1) && isValidNumber(newValue1) && !"0.000".equals(oldValue1)) {
                                newValue1 = new BigDecimal(oldValue1).add(new BigDecimal(newValue1)).toString();
                            }
                            result.put("关注类金额-合计", newValue1);

                            //result.put("企业未结清余额-合计", lines[i].split(" ")[8]);
                            String oldValue2 = result.getOrDefault("企业未结清余额-合计", "0.000").toString();
                            String newValue2 = lines[i].split(" ")[8];
                            if (StringUtils.isNotBlank(newValue2) && isValidNumber(newValue2) && !"0.000".equals(oldValue2)) {
                                newValue2 = new BigDecimal(oldValue2).add(new BigDecimal(newValue2)).toString();
                            }
                            result.put("企业未结清余额-合计", newValue2);
                            // 担保单位 需要的字段
                            result.put("担保单位-不良类金额-合计", newValue);
                        }
                        if (
                                lines[i].contains("非循环信用额度")
                                        || i - startIndex > 45
                        ) {
                            sign = false;
                        }
                    }

                }
            }
        }
    }

    private static void parseLiabilitiesHistory(String[] lines, Map<String, Object> result) {
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].contains("本金逾期")) {
                i++;
                if (lines[i].contains("账户数")) {
                    i++;
                    if (lines[i].contains("逾期")) {
                        if (lines[i + 1].contains("本金")) {
                            i++;
                        }

                        StringBuilder s = new StringBuilder();
                        //需要获取累加值------逾期总额
                        while (!lines[i].contains("基本信息")) {
                            i++;//取第一条
                            s.append(lines[i]);
                            if (i > 100) {
                                break;
                            }
                        }

                        StringParser sp = new StringParser();
                        List<List<String>> groups = sp.parseString(s.toString(), 11);
                        String sum = sp.parseSum(groups);
                        result.put("逾期类负债-逾期总额", sum);

                        getTrueOrFalse(result, sum, "出现贷款逾期或欠息情况", "出现贷款逾期或欠息情况");

                        //取第一条
                        List<String> list = groups.get(0);
                        result.put("全部负债-账户数", list.get(1));
                        result.put("全部负债-余额", list.get(2));

                        result.put("关注类负债-账户数", list.get(3));
                        result.put("关注类负债-余额", list.get(4));

                        result.put("不良类负债-账户数", list.get(5));
                        result.put("不良类负债-余额", list.get(6));

                        result.put("逾期类负债-逾期账户数", list.get(7));
                        result.put("逾期类负债-逾期总额", list.get(8));//后续需要获取累加值
                        result.put("逾期类负债-本金逾期账户数", list.get(9));
                        result.put("逾期类负债-逾期本金", list.get(10));

                    }
                }
            }
        }
    }

    // 解析企业基本信息
    private static void parseBasicInfo(String[] lines, Map<String, Object> result) {
        Map<String, String> basicInfo = new HashMap<>();
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].contains("企业名称")) {
                basicInfo.put("企业名称", lines[i].split(" ")[1]);
                result.put("企业名称", lines[i].split(" ")[1]);
            } else if (lines[i].contains("经济类型")) {
                basicInfo.put("经济类型", lines[i].split(" ")[1]);
            } else if (lines[i].contains("企业规模")) {
                basicInfo.put("企业规模", lines[i].split(" ")[1]);
            } else if (lines[i].contains("所属行业")) {
                basicInfo.put("所属行业", lines[i].split(" ")[1]);
            } else if (lines[i].contains("成立年份")) {
                basicInfo.put("成立年份", lines[i].split(" ")[1]);
            } else if (lines[i].contains("登记地址")) {
                basicInfo.put("登记地址", lines[i].split(" ")[1]);
            } else if (lines[i].contains("办公/经营地址")) {
                basicInfo.put("办公/经营地址", lines[i].split(" ")[1]);
            } else if (lines[i].contains("存续状态")) {
                basicInfo.put("存续状态", lines[i].split(" ")[1]);
            }
        }
        result.put("基本信息", basicInfo);
    }

    // 解析身份标识信息
    public static Map<String, String> parseIdentityInfo(String[] lines) {
        Map<String, String> identityInfo = new HashMap<>();
        boolean startParsing = false;
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].equals("身份标识")) {
                startParsing = true;
            } else if (startParsing) {
                String[] parts = lines[i].split(" ");
                if (parts.length >= 2) {
                    identityInfo.put(parts[0], parts[1]);
                }
            }
        }
        return identityInfo;
    }

    // 解析信息概要
    private static void parseInfoSummary(String[] lines, Map<String, Object> result) {
        Map<String, String> infoSummary = new HashMap<>();
        boolean startParsing = false;
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].equals("信息概要")) {
                startParsing = true;
            } else if (startParsing && lines[i].contains("首次有信贷交易的年份")) {
                String[] values = lines[i + 5].split(" ");
                infoSummary.put("首次有信贷交易的年份", values[0]);
                infoSummary.put("发生信贷交易的机构数", values[1]);
                infoSummary.put("当前有未结清信贷交易的机构数", values[2]);
                infoSummary.put("首次有相关还款责任的年份", values[3]);
                break;
            }
        }
        result.put("信息概要", infoSummary);
    }


    // 解析报告基本信息（报告编号、查询机构、报告时间、查询原因）
    public static void parseFileBasicInfo(String[] lines, Map<String, Object> result) {
        Map<String, String> basicInfo = new HashMap<>();
        for (int i = 0; i < lines.length; i++) {
            if (StringUtils.isBlank(lines[i])) {
                continue;
            }
            lines[i] = lines[i].trim();
            if (lines[i].startsWith("报告编号：")) {
                basicInfo.put("报告编号", lines[i].split("：")[1].trim());
            } else if (lines[i].contains("查询机构：")) {
                basicInfo.put("查询机构", lines[i].split("：")[1].trim());
                result.put("当前解析到的公司名称", lines[i].split("：")[1].trim());
            } else if (lines[i].contains("报告时间：")) {
                basicInfo.put("报告时间", lines[i].split("：")[1].trim());
            } else if (lines[i].contains("查询原因：")) {
                basicInfo.put("查询原因", lines[i].split("：")[1].trim());
            }
        }
        result.put("报告基本信息", basicInfo);
    }

    // 解析身份标识信息
    public static void parseIdentityInfo(String[] lines, Map<String, Object> result) {
        Map<String, String> identityInfo = new HashMap<>();
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].equals("身份标识")) {
                if (lines[i].contains("信息概要")) {
                    break;
                }
                for (int j = 0; j < 5; j++) {
                    i++;
                    String[] parts = lines[i].split(" ");
                    if (parts.length >= 2) {
                        identityInfo.put(parts[0], parts[1]);
                    }
                }

            }
        }
        result.put("身份标识", identityInfo);
    }


    // 解析借贷交易和担保交易
    private static void parseCreditAndGuaranteeTransactions(String[] lines, Map<String, Object> result) {
        Map<String, Object> transactions = new HashMap<>();
        Map<String, String> creditTransaction = new HashMap<>();
        Map<String, String> guaranteeTransaction = new HashMap<>();

        for (int i = 0; i < lines.length; i++) {
            if (lines[i].contains("借贷交易 担保交易")) {
                i++;
                if (lines[i].contains("余额")) {
                    creditTransaction.put("借贷交易-余额", lines[i].split(" ")[1]);
                    String orDefault = (String) result.getOrDefault("担保交易-余额", "");
                    if (StringUtils.isNotBlank(orDefault)) {
                        guaranteeTransaction.put("担保交易-余额", lines[i].split(" ")[3]);
                    }
                }
                i++;
                if (lines[i].contains("其中：被追偿余额")) {
                    creditTransaction.put("借贷交易-被追偿余额", lines[i].split(" ")[1]);
                    guaranteeTransaction.put("担保交易-关注类余额", lines[i].split(" ")[3]);
                }
                i++;
                if (lines[i].contains("关注类余额")) {
                    creditTransaction.put("借贷交易-关注类余额", lines[i].split(" ")[1]);
                    guaranteeTransaction.put("担保交易-不良类余额", lines[i].split(" ")[3]);
                }
                i++;
                if (lines[i].contains("不良类余额")) {
                    creditTransaction.put("借贷交易-不良类余额", lines[i].split(" ")[1]);
                }
            }
        }
        transactions.put("借贷交易", creditTransaction);
        transactions.put("担保交易", guaranteeTransaction);
        result.put("借贷交易和担保交易", transactions);
    }

    // 解析包含非信贷交易账户数等信息的表格
    private static void parseOtherDetails(String[] lines, Map<String, Object> result) {
        Map<String, String> otherDetails = new HashMap<>();
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].contains("非信贷交易账户数 欠税记录条数 民事判决记录条数 强制执行记录条数 行政处罚记录条数")) {
                i++;
                otherDetails.put("非信贷交易账户数", lines[i].split(" ")[0]);
                otherDetails.put("欠税记录条数", lines[i].split(" ")[1]);
                otherDetails.put("民事判决记录条数", lines[i].split(" ")[2]);
                otherDetails.put("强制执行记录条数", lines[i].split(" ")[3]);
                otherDetails.put("行政处罚记录条数", lines[i].split(" ")[4]);
            }
        }
        result.put("记录统计", otherDetails);
    }


    private static void getTrueOrFalse(Map<String, Object> result, String stringValue, String trueKey, String falseKey) {
        try {
            // 将字符串转换为BigDecimal
            BigDecimal bigDecimal = new BigDecimal(stringValue);
            // 判断是否大于0
            if (bigDecimal.compareTo(BigDecimal.ZERO) > 0) {
                System.out.println("数字大于0");
                result.put(falseKey, 0);
                result.put(trueKey, 1);
            } else {
                System.out.println("数字不大于0");
                result.put(falseKey, 1);
                result.put(trueKey, 0);
            }
        } catch (NumberFormatException e) {
            // 处理字符串无法转换为数字的情况
            System.out.println("字符串无法转换为数字");
            result.put(trueKey, 0);
            result.put(falseKey, 0);
        }
    }

}